//
//  FXComposePictureViewCell.swift
//  微博(Swift)
//
//  Created by V on 16/1/11.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit


protocol FXComposePictureViewCellDelegate: NSObjectProtocol{
    func deleteButtonClick(indexPath: NSIndexPath)
}

class FXComposePictureViewCell: UICollectionViewCell {
    
    // 给 cell 设置一个属性，给外界提供一个赋值的接口
    var image: UIImage? {
        didSet {
            if image == nil {
                // 当前显示加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                // 隐藏删除按钮
                deleteButton.hidden = true
            }else{
                // 这里不加这一句，显示加好的cell 重用会导致新添加的图片上边没有 删除按钮
                deleteButton.hidden = false
                // 取消高亮状态
                imageView.highlightedImage = nil
                imageView.image = image
            }
        }
    }
    
    // 定义一个代理属性
    weak var delegate: FXComposePictureViewCellDelegate?
    // 记录当前 cell 在哪一个位置，以便在删除的时候告诉外界要删除哪一个元素
    var indexPath: NSIndexPath?
    
    
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    // MARK: - 懒加载
    // 每一个 item 的imageView
    private lazy var imageView: UIImageView = UIImageView()
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return button
    }()
    
    
    
    
    // MARK: - 设置UI
    private func setupUI(){
        // 添加子控件
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        // 子控件的约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
    }
    
    
    
    
    // MARK: - 点击删除按钮执行的方法
    @objc private func deleteButtonClick(){
        delegate?.deleteButtonClick(indexPath!)
    }
}
